<template>
  <LoginCheck>
    <div class="wallet">
      <!-- 余额概览 -->
      <div class="balance-overview">
        <div class="total-balance">
          <span class="label">总余额</span>
          <span class="amount">¥{{ totalBalance }}</span>
        </div>
        <div class="card-count">
          <span class="label">储值卡</span>
          <span class="count">{{ cards.length }}张</span>
        </div>
      </div>

      <!-- 储值卡列表 -->
      <div class="card-list">
        <div class="section-title">我的储值卡</div>
        <div v-for="card in cards" :key="card.id" class="card-item" @click="viewCardDetail(card)">
          <div class="card-header">
            <div class="store-info">
              <img :src="card.store_logo" :alt="card.store_name" />
              <div class="store-details">
                <h4>{{ card.store_name }}</h4>
                <p>{{ card.card_number }}</p>
              </div>
            </div>
            <div class="card-status" :class="card.status" :data-status="card.status">
              {{ getStatusText(card.status) }}
            </div>
          </div>
          
          <div class="card-body">
            <div class="balance-info">
              <div class="current-balance">
                <span class="label">当前余额</span>
                <span class="amount">¥{{ card.current_amount }}</span>
              </div>
              <div class="original-amount">
                <span class="label">原始金额</span>
                <span class="amount">¥{{ card.original_amount }}</span>
              </div>
            </div>
            
            <div class="validity">
              <van-icon name="clock-o" />
              <span>有效期至：{{ formatDate(card.valid_until) }}</span>
            </div>
          </div>
          
          <div class="card-actions">
            <van-button size="small" type="primary" @click.stop="useCard(card)">使用</van-button>
            <van-button size="small" @click.stop="viewHistory(card)">消费记录</van-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="cards.length === 0" class="empty-state">
        <van-empty description="暂无储值卡" />
        <van-button type="primary" @click="goToHome">去拼购</van-button>
      </div>
    </div>
  </LoginCheck>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { showToast } from 'vant'
import LoginCheck from '@/components/LoginCheck.vue'

// 储值卡数据类型定义
interface StoredValueCard {
  id: number
  store_name: string
  store_logo: string
  card_number: string
  original_amount: number
  current_amount: number
  status: string
  valid_until: string
}

const router = useRouter()
const authStore = useAuthStore()

// 储值卡数据
const cards = ref<StoredValueCard[]>([])
const loading = ref(false)

// 获取用户储值卡
const fetchCards = async () => {
  if (!authStore.userInfo?.phone) {
    showToast('请先登录')
    return
  }

  loading.value = true
  try {
    const response = await fetch(`/api/user/stored-value-cards?phone=${authStore.userInfo.phone}`)
    
    if (!response.ok) {
      throw new Error('获取储值卡失败')
    }
    
    const data = await response.json()
    cards.value = data
  } catch (error) {
    console.error('获取储值卡错误:', error)
    showToast('获取储值卡失败')
  } finally {
    loading.value = false
  }
}

// 计算总余额
const totalBalance = computed(() => {
  return cards.value.reduce((sum, card) => sum + card.current_amount, 0)
})

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    '1': '正常',
    '0': '已用完',
    'active': '正常',
    'used': '已用完',
    'expired': '已过期'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 查看卡片详情
const viewCardDetail = (card: StoredValueCard) => {
  console.log('查看卡片详情', card)
  // TODO: 实现卡片详情页面
}

// 使用储值卡
const useCard = (card: StoredValueCard) => {
  console.log('使用储值卡', card)
  // TODO: 实现储值卡使用功能
}

// 查看消费记录
const viewHistory = (card: StoredValueCard) => {
  console.log('查看消费记录', card)
  // TODO: 实现消费记录页面
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

// 页面加载时获取储值卡数据
onMounted(() => {
  fetchCards()
})
</script>

<style scoped>
.wallet {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px; /* 额外底部边距，确保内容不被tabbar遮挡 */
}

.balance-overview {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px 20px;
  text-align: center;
}

.total-balance {
  margin-bottom: 20px;
}

.total-balance .label {
  display: block;
  font-size: 14px;
  margin-bottom: 5px;
}

.total-balance .amount {
  font-size: 32px;
  font-weight: bold;
}

.card-count {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-count .label {
  font-size: 14px;
}

.card-count .count {
  font-size: 16px;
  font-weight: bold;
}

.card-list {
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
}

.card-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.store-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.store-info img {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  object-fit: cover;
}

.store-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.store-details p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.card-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.card-status.active {
  background: #e8f5e8;
  color: #52c41a;
}

.card-status.used {
  background: #f5f5f5;
  color: #999;
}

.card-status.expired {
  background: #fff2f0;
  color: #ff4d4f;
}

/* 数字状态值样式 */
.card-status[data-status="1"] {
  background: #e8f5e8;
  color: #52c41a;
}

.card-status[data-status="0"] {
  background: #f5f5f5;
  color: #999;
}

.card-body {
  margin-bottom: 15px;
}

.balance-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.current-balance, .original-amount {
  text-align: center;
}

.current-balance .label, .original-amount .label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.current-balance .amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.original-amount .amount {
  font-size: 14px;
  color: #999;
}

.validity {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #666;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}
</style> 